package com.szh.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.szh.common.constant.ProductConstant;
import com.szh.common.dto.SkuHasStockVo;
import com.szh.common.dto.SkuReductionDto;
import com.szh.common.dto.SpuBoundsDto;
import com.szh.common.dto.es.SkuEsModel;
import com.szh.common.utils.R;
import com.szh.gulimall.product.dao.AttrDao;
import com.szh.gulimall.product.entity.*;
import com.szh.gulimall.product.feign.CouponFeignService;
import com.szh.gulimall.product.feign.SearchFeignService;
import com.szh.gulimall.product.feign.WareFeignService;
import com.szh.gulimall.product.service.*;
import com.szh.gulimall.product.vo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szh.common.utils.PageUtils;
import com.szh.common.utils.Query;
import com.szh.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SpuInfoServiceImpl.class);

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private AttrService attrService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private ProductAttrValueService attrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    /**
     * 保存spu基本信息
     * @GlobalTransactional: seata处理全局分布式事务注解
     * 商品服务中调用了优惠服务，如果商品服务出异常，此注解可保证商品、优惠服务的数据都回滚
     */
    @Override
    @Transactional
//    @GlobalTransactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);
        //2.保存spu的描述信息 pms_spu_info_desc
        List<String> decriptList = spuSaveVo.getDecript();
        if (!CollectionUtils.isEmpty(decriptList)) {
            SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
            descEntity.setSpuId(spuInfoEntity.getId());
            descEntity.setDecript(String.join(",", decriptList));
            spuInfoDescService.saveSpuInfoDesc(descEntity);
        }
        //3.保存spu的图片集 pms_spu_images
        List<String> imagesList = spuSaveVo.getImages();
        if (!CollectionUtils.isEmpty(imagesList)) {
            spuImagesService.saveSpuImages(spuInfoEntity.getId(), imagesList);
        }
        //4.保存spu的规格参数/基本属性 pms_product_attr_value
        List<BaseAttrs> baseAttrsList = spuSaveVo.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrsList)) {
            List<Long> attrIds = baseAttrsList.stream().map(BaseAttrs::getAttrId).collect(Collectors.toList());
            List<AttrEntity> attrEntityList = attrDao.selectBatchIds(attrIds);
            Map<Long, String> attrInfoMap = attrEntityList.stream().collect(Collectors.toMap(AttrEntity::getAttrId, AttrEntity::getAttrName));
            List<ProductAttrValueEntity> attrValueEntityList = baseAttrsList.stream().map(attr -> {
                ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
                attrValueEntity.setSpuId(spuInfoEntity.getId());
                attrValueEntity.setAttrId(attr.getAttrId());
                attrValueEntity.setAttrName(attrInfoMap.get(attr.getAttrId()));
                attrValueEntity.setAttrValue(attr.getAttrValues());
                attrValueEntity.setQuickShow(attr.getShowDesc());
                return attrValueEntity;
            }).collect(Collectors.toList());
            attrValueService.saveProductAttrValue(attrValueEntityList);
        }
        //5.保存spu的积分信息 sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsDto spuBoundsDto = new SpuBoundsDto();
        BeanUtils.copyProperties(bounds, spuBoundsDto);
        spuBoundsDto.setSpuId(spuInfoEntity.getId());
        R result = couponFeignService.saveSpuBounds(spuBoundsDto);
        if (result.getCode() != 0) {
            LOGGER.error("远程保存spu积分信息失败....");
        }
        //6.保存spu的所有sku信息
        List<Skus> skuList = spuSaveVo.getSkus();
        if (!CollectionUtils.isEmpty(skuList)) {
            //6.1 保存sku的基本信息 pms_sku_info
            List<SkuInfoEntity> skuInfoEntityList = skuList.stream().map(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                return skuInfoEntity;
            }).collect(Collectors.toList());
            skuInfoService.saveSkuInfo(skuInfoEntityList);
            //6.2 保存sku的图片集 pms_sku_images
            //6.3 保存sku的销售属性 pms_sku_sale_attr_value
            List<SkuImagesEntity> skuImagesEntityList = new ArrayList<>();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntityList = new ArrayList<>();
            for (int i = 0; i < skuInfoEntityList.size(); i++) {
                List<Images> images = skuList.get(i).getImages();
                for (Images image : images) {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntityList.get(i).getSkuId());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntityList.add(skuImagesEntity);
                }
                List<Attr> attrs = skuList.get(i).getAttr();
                for (Attr attr : attrs) {
                    SkuSaleAttrValueEntity saleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuInfoEntityList.get(i).getSkuId());
                    skuSaleAttrValueEntityList.add(saleAttrValueEntity);
                }
            }
            List<SkuImagesEntity> resultList = skuImagesEntityList.stream()
                    .filter(item -> !StringUtils.isEmpty(item.getImgUrl())).collect(Collectors.toList());
            skuImagesService.saveSkuImages(resultList);
            skuSaleAttrValueService.saveSaleAttrValue(skuSaleAttrValueEntityList);
            //6.4 保存sku的优惠、满减等信息 sms_sku_ladder sms_sku_full_reduction sms_member_price
            int skuIndex = 0;
            for (Skus item : skuList) {
                SkuReductionDto skuReductionDto = new SkuReductionDto();
                BeanUtils.copyProperties(item, skuReductionDto);
                skuReductionDto.setSkuId(skuInfoEntityList.get(skuIndex++).getSkuId());
                if (skuReductionDto.getFullCount() > 0 ||
                        skuReductionDto.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R res = couponFeignService.saveSkuReduction(skuReductionDto);
                    if (res.getCode() != 0) {
                        LOGGER.error("远程保存sku优惠满减信息失败....");
                    }
                }
            }
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        baseMapper.insert(spuInfoEntity);
    }

    /**
     * 条件查询spu列表
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> obj.eq("id", key).or().like("spu_name", key));
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    /**
     * 商品上架
     */
    @Override
    public void spuUp(Long spuId) {
        //1.查询当前spuId对应的所有sku信息
        List<SkuInfoEntity> skuList = skuInfoService.getSkusBySpuId(spuId);
        //2.查询每个sku对应的分类、品牌信息
        List<Long> catalogIds = skuList.stream().map(SkuInfoEntity::getCatalogId).collect(Collectors.toList());
        Collection<CategoryEntity> categoryList = categoryService.listByIds(catalogIds);
        Map<Long, String> categoryNameMap = categoryList.stream().collect(Collectors.toMap(CategoryEntity::getCatId, CategoryEntity::getName));
        List<Long> brandIds = skuList.stream().map(SkuInfoEntity::getBrandId).collect(Collectors.toList());
        Collection<BrandEntity> brandList = brandService.listByIds(brandIds);
        Map<Long, String> brandNameMap = brandList.stream().collect(Collectors.toMap(BrandEntity::getBrandId, BrandEntity::getName));
        Map<Long, String> brandLogoMap = brandList.stream().collect(Collectors.toMap(BrandEntity::getBrandId, BrandEntity::getLogo));
        //3.查询每个sku中所有可以被用来检索的规格参数（当前spu的基本属性，在同一个spu下的所有sku共享这些属性，有些可检索，有些不可检索）
        List<ProductAttrValueEntity> baseAttrList = attrValueService.baseAttrListForSpu(spuId);
        List<Long> attrIds = baseAttrList.stream().map(ProductAttrValueEntity::getAttrId).collect(Collectors.toList());
        //在上一步指定的属性集合中查询出可以被检索的那些属性id
        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        Set<Long> set = new HashSet<>(searchAttrIds);
        //从所有的属性中过滤出那些可以被检索的属性信息
        List<SkuEsModel.Attrs> attrs = baseAttrList.stream()
                .filter(item -> set.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                }).collect(Collectors.toList());
        //4.拿到所有sku的id集合
        List<Long> skuIds = skuList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //将每个sku是否有库存的信息，按照key为skuId、value为是否有库存，组装成Map
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getHasSkuStock(skuIds);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::getHasStock));
        } catch (Exception ex) {
            LOGGER.error("库存服务查询异常：{}", ex.getMessage());
        }
        Map<Long, Boolean> finalStockMap = stockMap;
        //5.封装每个sku的信息
        List<SkuEsModel> skuEsModelList = skuList.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, skuEsModel); //属性相同的直接拷贝
            skuEsModel.setSkuPrice(sku.getPrice()); //设置sku价格
            skuEsModel.setSkuImg(sku.getSkuDefaultImg()); //设置sku图片
            skuEsModel.setCatalogName(categoryNameMap.get(sku.getCatalogId())); //设置分类名称
            skuEsModel.setBrandName(brandNameMap.get(sku.getBrandId())); //设置品牌名称
            skuEsModel.setBrandImg(brandLogoMap.get(sku.getBrandId())); //设置品牌图片
            skuEsModel.setAttrs(attrs); //设置可以检索的属性
            skuEsModel.setHotScore(0L); //设置热度评分
            if (CollectionUtils.isEmpty(finalStockMap)) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }
            return skuEsModel;
        }).collect(Collectors.toList());
        //6.将数据发送给ES进行保存
        R result = searchFeignService.productUp(skuEsModelList);
        if (result.getCode() == 0) { //远程调用成功
            //修改当前spu的状态为已上架
            baseMapper.updateSpuStatus(spuId, ProductConstant.SpuStatusEnum.SPU_UP.getCode());
        } else { //远程调用失败

        }
    }

    /**
     * 根据skuId查询对应的spu信息
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = this.getById(spuId);
        return spuInfoEntity;
    }

}